<template>
  <div class="space-y-6">
    <!-- 搜索和添加区域 -->
    <div class="flex justify-between">
      <div class="flex gap-4">
        <a-input-search
          v-model="searchParams.keyword"
          placeholder="请输入用户名/姓名搜索"
          style="width: 320px"
          @search="handleSearch"
          allow-clear
        />
        <a-select
          v-model="searchParams.userType"
          placeholder="请选择用户类型"
          style="width: 200px"
          @change="handleSearch"
          allow-clear
        >
          <a-option value="">全部类型</a-option>
          <a-option value="ADMIN">管理员</a-option>
          <a-option value="WORKER">工人</a-option>
          <a-option value="RENTAL_FACTORY">出租方</a-option>
          <a-option value="BORROWING_FACTORY">承租方</a-option>
          <a-option value="REPAIR_FACTORY">维修方</a-option>
        </a-select>
      </div>
      <a-button type="primary" @click="openAddModal">
        <template #icon><icon-plus /></template>
        添加用户
      </a-button>
    </div>

    <!-- 用户列表表格 -->
    <a-table
      :data="tableData"
      :loading="loading"
      :pagination="{
        total: pagination.total,
        current: pagination.current,
        pageSize: pagination.pageSize,
        showTotal: true,
        showJumper: true,
        showPageSize: true
      }"
      @page-change="onPageChange"
      @page-size-change="onPageSizeChange"
      stripe
    >
      <template #columns>
        <a-table-column title="用户名" data-index="username" />
        <a-table-column title="姓名" data-index="realName" />
        <a-table-column title="用户类型" data-index="userType">
          <template #cell="{ record }">
            <a-tag :color="getUserTypeColor(record.userType)">
              {{ getUserTypeLabel(record.userType) }}
            </a-tag>
          </template>
        </a-table-column>
        <a-table-column title="角色" data-index="roles">
          <template #cell="{ record }">
            <a-space>
              <a-tag 
                v-for="role in record.roles" 
                :key="role.roleId" 
                color="blue"
              >
                {{ role.name }}
              </a-tag>
            </a-space>
          </template>
        </a-table-column>
        <a-table-column title="邮箱" data-index="email" />
        <a-table-column title="手机号" data-index="mobile" />
        <a-table-column title="状态" data-index="status">
          <template #cell="{ record }">
            <a-tag :color="record.status === 1 ? 'green' : 'red'">
              {{ record.status === 1 ? '启用' : '禁用' }}
            </a-tag>
          </template>
        </a-table-column>
        <a-table-column title="最后登录时间" data-index="lastLoginTime" />
        <a-table-column title="操作" :width="operationColumnWidth">
          <template #cell="{ record }">
            <a-space>
              <a-button type="text" size="small" @click="editUser(record)">
                <template #icon><icon-edit /></template>
                编辑
              </a-button>
              <a-popconfirm
                content="确定要删除该用户吗？"
                @ok="deleteUser(record)"
              >
                <a-button type="text" status="danger" size="small">
                  <template #icon><icon-delete /></template>
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>

    <!-- 添加/编辑用户弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-align="right"
        :style="{ width: '600px' }"
      >
        <a-form-item field="username" label="用户名" v-if="!formData.userId">
          <a-input v-model="formData.username" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item field="password" label="密码" v-if="!formData.userId">
          <a-input-password v-model="formData.password" placeholder="请输入密码" />
        </a-form-item>
        <a-form-item field="userType" label="用户类型" v-if="!formData.userId">
          <a-select v-model="formData.userType" placeholder="请选择用户类型">
            <a-option value="ADMIN">管理员</a-option>
            <a-option value="WORKER">工人</a-option>
            <a-option value="RENTAL_FACTORY">出租方</a-option>
            <a-option value="BORROWING_FACTORY">承租方</a-option>
            <a-option value="REPAIR_FACTORY">维修方</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="realName" label="姓名">
          <a-input v-model="formData.realName" placeholder="请输入姓名" />
        </a-form-item>
        <a-form-item field="email" label="邮箱">
          <a-input v-model="formData.email" placeholder="请输入邮箱" />
        </a-form-item>
        <a-form-item field="mobile" label="手机号">
          <a-input v-model="formData.mobile" placeholder="请输入手机号" />
        </a-form-item>
        <a-form-item field="roleIds" label="角色">
          <a-select
            v-model="formData.roleIds"
            placeholder="请选择角色"
            multiple
          >
            <a-option
              v-for="role in roleOptions"
              :key="role.roleId"
              :value="role.roleId"
            >
              {{ role.name }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="status" label="状态" v-if="formData.userId">
          <a-radio-group v-model="formData.status">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="0">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconPlus, IconEdit, IconDelete } from '@arco-design/web-vue/es/icon'
import type { FieldRule } from '@arco-design/web-vue'
import { userApi } from '@/api/user'
import { roleApi } from '@/api/role'
import type { UserInfo, UserType, CreateUserParams, UpdateUserParams, Role } from '@/types/api'

// 搜索参数
const searchParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
  userType: '' as '' | UserType
})

// 表格相关
const loading = ref(false)
const tableData = ref<UserInfo[]>([])
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10
})

// 操作列宽度
const operationColumnWidth = 200

// 角色选项
const roleOptions = ref<Role[]>([])

// 模态框相关
const modalVisible = ref(false)
const modalTitle = ref('添加用户')
const formRef = ref<any>()
const formData = reactive({
  userId: 0,
  username: '',
  password: '',
  userType: '' as UserType,
  realName: '',
  email: '',
  mobile: '',
  status: 1,
  roleIds: [] as number[]
})

// 表单验证规则
const rules = computed(() => {
  const baseRules = {
    username: [{ required: !formData.userId, message: '请输入用户名' }],
    password: [{ required: !formData.userId, message: '请输入密码' }],
    userType: [{ required: !formData.userId, message: '请选择用户类型' }],
    realName: [{ required: true, message: '请输入姓名' }],
    email: [
      { required: true, message: '请输入邮箱' },
      { type: 'email', message: '请输入正确的邮箱格式' }
    ],
    mobile: [
      { required: true, message: '请输入手机号' },
      { match: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式' }
    ],
    roleIds: [{ required: true, message: '请选择角色', type: 'array' }]
  } as Record<string, FieldRule[]>
  return baseRules
})

// 用户类型工具函数
const userTypeMap = {
  'ADMIN': '管理员',
  'WORKER': '工人',
  'RENTAL_FACTORY': '出租方',
  'BORROWING_FACTORY': '承租方',
  'REPAIR_FACTORY': '维修方'
} as const

const getUserTypeLabel = (userType: string) => {
  return userTypeMap[userType as keyof typeof userTypeMap] || userType
}

const getUserTypeColor = (userType: string) => {
  const colorMap: Record<string, string> = {
    'ADMIN': 'red',
    'WORKER': 'blue',
    'RENTAL_FACTORY': 'green',
    'BORROWING_FACTORY': 'orange',
    'REPAIR_FACTORY': 'purple'
  }
  return colorMap[userType] || 'default'
}

// 获取用户列表
const fetchUserList = async () => {
  try {
    loading.value = true
    const res = await userApi.getUserList({
      page: pagination.current,
      size: pagination.pageSize,
      keyword: searchParams.keyword,
      userType: searchParams.userType
    })
    console.log('获取用户列表响应:', res)
    
    if (res.code === 1) {
      tableData.value = res.data.records
      pagination.total = res.data.total
    } else {
      Message.error(res.msg || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表错误:', error)
    Message.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 获取角色列表
const fetchRoleList = async () => {
  try {
    const res = await roleApi.getRoleList({
      page: 1,
      size: 100
    })
    console.log('获取角色列表响应:', res)
    
    if (res.code === 1) {
      roleOptions.value = res.data.records
    } else {
      Message.error(res.msg || '获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表错误:', error)
    Message.error('获取角色列表失败')
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.current = 1
  fetchUserList()
}

// 处理分页变化
const onPageChange = (page: number) => {
  pagination.current = page
  fetchUserList()
}

// 处理每页条数变化
const onPageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.current = 1
  fetchUserList()
}

// 打开添加用户弹窗
const openAddModal = () => {
  modalTitle.value = '添加用户'
  formData.userId = 0
  formData.username = ''
  formData.password = ''
  formData.userType = '' as UserType
  formData.realName = ''
  formData.email = ''
  formData.mobile = ''
  formData.status = 1
  formData.roleIds = []
  modalVisible.value = true
}

// 编辑用户
const editUser = (record: UserInfo) => {
  modalTitle.value = '编辑用户'
  formData.userId = record.userId
  formData.username = record.username
  formData.userType = record.userType
  formData.realName = record.realName
  formData.email = record.email
  formData.mobile = record.mobile
  formData.status = record.status
  formData.roleIds = record.roles?.map(role => role.roleId) || []
  modalVisible.value = true
}

// 删除用户
const deleteUser = async (record: UserInfo) => {
  try {
    const res = await userApi.deleteUser(record.userId)
    if (res.code === 1) {
      Message.success('删除成功')
      fetchUserList()
    } else {
      Message.error(res.msg || '删除失败')
    }
  } catch (error) {
    console.error('删除用户错误:', error)
    Message.error('删除失败')
  }
}

// 处理弹窗确认
const handleModalOk = async () => {
  try {
    console.log('开始表单验证')
    await formRef.value?.validate()
    console.log('表单验证通过')
    
    if (formData.userId) {
      // 编辑用户
      const updateParams: UpdateUserParams = {
        userId: formData.userId,
        username: formData.username,
        realName: formData.realName,
        email: formData.email,
        mobile: formData.mobile,
        status: formData.status,
        userType: formData.userType,
        roleIds: formData.roleIds
      }
      console.log('准备更新用户，参数:', updateParams)
      try {
        console.log('发送更新用户请求')
        const res = await userApi.updateUser(updateParams)
        console.log('收到更新用户响应:', res)
        
        if (res.code === 1) {
          console.log('更新用户成功')
          Message.success('更新用户成功')
          modalVisible.value = false
          fetchUserList()
        } else {
          console.error('更新用户失败:', res)
          Message.error(res.msg || '更新用户失败')
        }
      } catch (error) {
        console.error('更新用户请求失败:', error)
        Message.error('更新用户失败，请稍后重试')
      }
    } else {
      // 创建用户
      const createParams: CreateUserParams = {
        username: formData.username,
        password: formData.password,
        confirmPassword: formData.password,
        realName: formData.realName,
        email: formData.email,
        mobile: formData.mobile,
        userType: formData.userType
      }

      try {
        // 先创建用户
        console.log('发送创建用户请求')
        const res = await userApi.createUser(createParams)
        console.log('收到创建用户响应:', res)
        
        // 如果创建成功且有选择角色，则更新用户角色
        // if (res.code === 1 && res.data) {
        if (res.code === 1) {
          if (formData.roleIds.length > 0) {
            const updateRoleRes = await userApi.updateUser({
              userId: Number(res.data),
              username: formData.username,
              realName: formData.realName,
              email: formData.email,
              mobile: formData.mobile,
              status: 1,
              userType: formData.userType,
              roleIds: formData.roleIds
            })
            if (updateRoleRes.code !== 1) {
              Message.warning('用户创建成功，但角色分配失败')
              modalVisible.value = false
              fetchUserList()
              return
            }
          }
          
          console.log('创建用户成功')
          Message.success('创建用户成功')
          modalVisible.value = false
          fetchUserList()
        } else {
          console.error('创建用户失败:', res)
          Message.error(res.msg || '创建用户失败')
        }
      } catch (error) {
        console.error('创建用户请求失败:', error)
        Message.error('创建用户失败，请稍后重试')
      }
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    Message.error('请检查表单填写是否正确')
    return
  }
}

// 处理模态框取消
const handleModalCancel = () => {
  modalVisible.value = false
  formRef.value?.resetFields()
}

// 初始化
onMounted(() => {
  fetchUserList()
  fetchRoleList()
})
</script> 